﻿using ClumsyWords.DataModel;
using ClumsyWords.Portable.Model;
using System;
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.ApplicationModel.DataTransfer;
using System.Collections;
using System.Collections.ObjectModel;

// The Item Detail Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234232

namespace ClumsyWords
{
    /// <summary>
    /// A page that displays details for a single item within a group while allowing gestures to
    /// flip through other items belonging to the same group.
    /// </summary>
    public sealed partial class ItemDetailPage : ClumsyWords.Common.LayoutAwarePage
    {

        public ItemDetailPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            // Allow saved page state to override the initial item to display
            if (pageState != null && pageState.ContainsKey("SelectedItem"))
            {
                navigationParameter = pageState["SelectedItem"];
            }

            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            var item = DefinitionsDataSource.Instance.GetItem((Guid)navigationParameter);

            //TODO: Implement a GridView just like in the GroupedItemsPage to display item properties grouped by part of speech
            //this.DefaultViewModel["Items"] = DefinitionsDataSource.Instance.GetGroup("Recent").Items;
            this.DefaultViewModel["Groups"] = item.Items;
            this.DefaultViewModel["CurrentItem"] = item;

            DataTransferManager.GetForCurrentView().DataRequested += OnDataRequested;
        }

        #region Share Functionality Methods

        private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            var request = args.Request;
            var item = (DefinitionsDataItem)this.DefaultViewModel["CurrentItem"];

            request.Data.Properties.Title = item.Term;

            string definitionsString = "<style>body{word-wrap:break-word;} h2{text-align:center;}</style>";

            if(this.itemGridView.SelectedItems.Count == 0)
                definitionsString += GetHtmlFormattedText(item);

            else
            {
                List<TermProperties> selectedItems = new List<TermProperties>();
                TermProperties currentItem;

                foreach (var selectedItem in this.itemGridView.SelectedItems)
                {
                    currentItem = (TermProperties)selectedItem;

                    if (!selectedItems.Contains(currentItem))
                        selectedItems.Add(currentItem);
                }
                definitionsString = GetHtmlFormattedText(item, DefinitionsDataItem.GetGroupsList(selectedItems, p => p.PartOfSpeech));
            }

            definitionsString = HtmlFormatHelper.CreateHtmlFormat(definitionsString);
            request.Data.SetHtmlFormat(definitionsString);
        }

        #endregion

        void Header_Click(object sender, RoutedEventArgs e)
        {
            // Determine what group the Button instance represents
            var group = (sender as FrameworkElement).DataContext;

            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            this.Frame.Navigate(typeof(ItemGroupDetailPage), (CommonGroup<TermProperties>)group);
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
            DataTransferManager.GetForCurrentView().DataRequested -= OnDataRequested;
        }

        private void OnGridViewSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            #region Maintain Selection Across View States
            foreach (var item in e.RemovedItems)
            {
                this.itemListView.SelectedItems.Remove(item);
            }

            foreach (var item in e.AddedItems)
            {
                this.itemListView.SelectedItems.Add(item);
            }
            #endregion

            if (this.itemGridView.SelectedItems.Count == 0)
            {
                //this.BottomAppBar.IsSticky = false;
                this.BottomAppBar.IsOpen = false;
            }
            else
            {
                this.BottomAppBar.IsOpen = true;
                //this.BottomAppBar.IsSticky = true;
            }
        }

        private void OnListViewSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            #region Maintain Selection Across View States
            foreach (var item in e.RemovedItems)
            {
                this.itemGridView.SelectedItems.Remove(item);
            }

            foreach (var item in e.AddedItems)
            {
                this.itemGridView.SelectedItems.Add(item);
            }
            #endregion

            if (this.itemGridView.SelectedItems.Count == 0)
            {
                this.BottomAppBar.IsOpen = false;
            }
            else
            {
                this.BottomAppBar.IsOpen = true;
            }
        }

        private void OnAddToFavouritesClick(object sender, RoutedEventArgs e)
        {
            DefinitionsDataItem newItem = new DefinitionsDataItem();
            string currentTerm = ((DefinitionsDataItem)this.DefaultViewModel["CurrentItem"]).Term;
            List<TermProperties> selectedItems = new List<TermProperties>();
            TermProperties currentItem;

            foreach (var item in this.itemGridView.SelectedItems)
            {
                currentItem = (TermProperties)item;

                if (!selectedItems.Contains(currentItem))
                    selectedItems.Add(currentItem);
            }

            newItem.ComposeItemFromTermProperties(currentTerm, selectedItems);
            DefinitionsDataSource.Instance.GetGroup("Favourites").Items.Add(newItem);
            this.Frame.Navigate(typeof(GroupedItemsPage), "Recent Favourites");
        }

        private void OnClearSelectionClick(object sender, RoutedEventArgs e)
        {
            if (this.itemGridView.SelectedItems.Count != 0)
                this.itemGridView.SelectedItems.Clear();
        }

        private void OnGoHomeClick(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(GroupedItemsPage), "Recent Favourites");
        }

        private void OnSemanticZoomViewChangeStarted(object sender, SemanticZoomViewChangedEventArgs e)
        {
            if (e.IsSourceZoomedInView == true)
                this.BottomAppBar.Visibility = Visibility.Collapsed;
            else
                this.BottomAppBar.Visibility = Visibility.Visible;
        }
    }
}
